import 'package:flutter_wear_app/utils/http_util.dart';
import 'package:hive/hive.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tencent_rtc_sdk/trtc_cloud.dart';
import 'package:tencent_rtc_sdk/trtc_cloud_def.dart';
import 'package:tencent_rtc_sdk/trtc_cloud_listener.dart';

late TRTCCloud trtcCloud;
final box = Hive.box('myBox');
final trtcParms = {
  "sdkAppId": 0,
  "userId": "",
  "strRoomId": "",
  "userSig": "",
  "role": TRTCRoleType.anchor,
  "isCreate": false, // 是否创建房间
};

// 创建 TRTCCloudListener 实例
TRTCCloudListener listener = TRTCCloudListener(
  // 根据需要实现对应的回调
  onEnterRoom: (result) => {print('onEnterRoom: $result')},
  // 根据需要实现对应的回调
  onError: (errCode, errMsg) {
    // TODO
  },
  onExitRoom: (reason) {
    // TODO
  },
);

Future<void> initTrtc() async {
  // 创建 TRTC 实例
  trtcCloud = await TRTCCloud.sharedInstance();
  // 注册监听器，将 listener 绑定到 trtcCloud 实例
  trtcCloud.registerListener(listener);

  if (!(await Permission.camera.request().isGranted) ||
      !(await Permission.microphone.request().isGranted)) {
    print('You need to obtain audio and video permission to enter');
    return;
  }
}

Future<void> entRoom({room_id = ""}) async {
  await getUserSign();
  if (room_id != "") {
    trtcParms['strRoomId'] = room_id;
  }
  await initTrtc();
  trtcCloud.enterRoom(
    TRTCParams(
      // Bug修复: 确保转换为 int 类型
      sdkAppId:
          trtcParms['sdkAppId'] is String
              ? int.parse(trtcParms['sdkAppId'] as String)
              : trtcParms['sdkAppId'] as int,
      userId: trtcParms['userId'] as String,
      strRoomId: trtcParms['strRoomId'] as String,
      userSig: trtcParms['userSig'] as String,
    ),
    TRTCAppScene.live,
  );
  trtcCloud.startLocalAudio(TRTCAudioQuality.speech);
}

Future<void> exitRoom() async {
  trtcCloud.exitRoom();
}

Future<void> getUserSign() async {
  final sdkAppId = box.get('tencent')['trtc_appId'];
  print("----------------------sdkAppId:$sdkAppId");
  final id = box.get('userInfo')['id'];
  final res = await HttpUtil.get('/app/getUserSign', params: {"user": id});
  if (res['code'] == 1) {
    trtcParms['userSig'] = res['data']['UserSign'];
    trtcParms['userId'] = res['data']['userId'];
    trtcParms['sdkAppId'] = sdkAppId;
    trtcParms['strRoomId'] = res['data']['roomId'];
  } else {
    print('获取用户签名失败');
  }
}
